<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="pl-2 pr-2">
      <div class="flex justify-center mb-2">
        <a-button type="primary" class="ml-2" @click="handleSave">保存</a-button>
        <a-button type="primary" class="ml-2" @click="handleAdd">增加</a-button>
        <!-- <a-button type="primary" class="ml-2" @click="fetch">查询</a-button> -->
      </div>
      <draggable
        v-model="list"
        :component-data="{
          type: 'transition-group',
        }"
        :animation="180"
        handle=".draggable-item"
        item-key="id"
      >
        <template #item="{ element, index }">
          <Card style="margin-bottom: 5px" :bodyStyle="{ padding: '12px' }">
            <div class="flex items-center justify-between">
              <div class="w-1/24">如果</div>
              <div class="flex flex-col w-10/24">
                <div
                  class="flex items-center mb-1 w-10/24"
                  v-for="(el, elIndex) in element.childLeft"
                  :key="`26${el}`"
                >
                  <div>
                    <Select
                      :options="formGetFields"
                      class="w-30"
                      v-model:value="el['field']"
                      @change="(val) => getFieldsChange(val, el)"
                    />
                  </div>
                  <div class="ml-1 mr-1">
                    <Select :options="compareOptions" class="w-20" v-model:value="el['operator']" />
                  </div>
                  <div class="flex items-center">
                    <Input
                      v-if="el['val'] == '{$curDate}' || el['val'] == '{$curUser}'"
                      v-model:value="el['curTypeName']"
                      readonly
                      style="width: 150px; margin-right: 5px"
                    />

                    <Input
                      v-else-if="el['val'] == 'null'"
                      v-model:value="el['val']"
                      style="width: 150px; margin-right: 5px"
                    />
                    <Select
                      v-else-if="el['mainFormOpt']"
                      :options="formGetFieldsMain"
                      v-model:value="el['val']"
                      style="width: 150px; margin-right: 5px"
                    />
                    <template v-else>
                      <FormCtl
                        v-if="el['field'] && el['formCode']"
                        :formCode="el['formCode']"
                        :fieldName="el['field']"
                        v-model:value="el['val']"
                        style="width: 150px; margin-right: 5px"
                      />

                      <Select
                        v-else-if="el['field'] == 'cws_role'"
                        :options="roleList"
                        v-model:value="el['val']"
                        style="width: 150px; margin-right: 5px"
                      />
                      <Input
                        v-else
                        v-model:value="el['val']"
                        style="width: 150px; margin-right: 5px"
                      />
                    </template>
                    <Dropdown>
                      <DownOutlined />
                      <template #overlay>
                        <Menu @click="({ key }) => handleClickMenu(key, el)">
                          <MenuItem :key="k.value" v-for="k in itemKeys">
                            {{ k.label }}
                          </MenuItem>
                        </Menu>
                      </template>
                    </Dropdown>
                  </div>
                  <div class="ml-2 cursor-pointer">
                    <PlusOutlined v-if="elIndex === 0" @click="handleLeftAdd({ element })" />
                    <MinusOutlined v-else @click="handleLeftDelete({ element, elIndex })" />
                  </div>
                </div>
              </div>
              <div class="p-2 w-1/24">则</div>
              <di class="w-10/24">
                <div
                  class="flex items-center mb-1"
                  v-for="(el, elIndex) in element.childRight"
                  :key="`363${el}`"
                >
                  <div>
                    <Select
                      :options="formElementsList"
                      class="w-200px"
                      v-model:value="el['field']"
                    />
                  </div>
                  <div class="ml-1 mr-1">
                    <Select
                      :options="fieldDisplayOptions"
                      class="w-20"
                      v-model:value="el['field_display']"
                    />
                  </div>
                  <div class="ml-2 cursor-pointer">
                    <PlusOutlined v-if="elIndex === 0" @click="handleRightAdd({ element })" />
                    <MinusOutlined v-else @click="handleRightDelete({ element, elIndex })" />
                  </div>
                </div>
              </di>
              <div class="w-2/24">
                <CloseOutlined class="cursor-pointer" @click="handleDelete({ index })" />
                <drag-outlined class="ml-2 cursor-pointer draggable-item" />
                <!-- <ArrowUpOutlined
                class="ml-2 mr-2 cursor-pointer"
                v-if="index != 0"
                @click="handleUpOrDown({ index, type: 'up' })"
              />
              <ArrowDownOutlined
                class="cursor-pointer"
                v-if="index != list.length - 1"
                @click="handleUpOrDown({ index, type: 'down' })"
              /> -->
              </div>
            </div>
          </Card>
        </template>
      </draggable>
      <div>
        注：<br />
        1、显示规则用于导出生成word文件<br />
        2、日期型字段格式，例：2020-10-08，2020-10-09 15:30:10，current表示当前日期
      </div>
    </div>
  </ScrollContainer>
</template>
<script lang="ts" setup>
  import { ref, unref, watch, onMounted, computed, nextTick } from 'vue';
  import { Card, Select, Dropdown, Menu, Checkbox, Input } from 'ant-design-vue';
  import { ScrollContainer } from '/@/components/Container';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FormCtl } from '/@/components/FormCtl';
  import draggable from 'vuedraggable';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  import { cloneDeep } from 'lodash-es';
  import { getRoleMultilSel } from '/@/api/system/system';
  import {
    PlusOutlined,
    MinusOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined,
    CloseOutlined,
    DownOutlined,
    DragOutlined,
  } from '@ant-design/icons-vue';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import {
    getFormViewGetViewRule,
    getFormViewUpdateViewSetup,
    getFormViewGetElements,
  } from '/@/api/formDesign/formDesign';
  import {
    down,
    up,
    leftAddRow,
    rightAddRow,
    compareOptions,
    fieldDisplayOptions,
    getviews,
    itemKeys,
    setviews,
  } from './displayRules.data';
  import { isArray } from '/@/utils/is';
  import { getUUID } from '/@/views/formDesigner/utils/common/string';
  const MenuItem = Menu.Item;
  const { createMessage, createConfirm } = useMessage();
  const props = defineProps({
    mainId: {
      type: String as PropType<string>,
      default: '',
    },
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
  });
  const loading = ref(false);
  const typeCode = computed(() => '');

  const list: any = ref([]);

  //主表删除
  const handleDelete = ({ index }) => {
    list.value.splice(index, 1);
  };
  //主表新增
  const handleAdd = () => {
    const mainAddRow = {
      id: getUUID(),
      childLeft: [
        {
          field: '',
          operator: '',
          val: '',
        },
      ],
      childRight: [
        {
          field: '',
          field_display: 'show',
        },
      ],
    };
    list.value.push(cloneDeep(mainAddRow));
  };

  //主表排序
  const handleUpOrDown = ({ index, type }) => {
    let arr = JSON.parse(JSON.stringify(unref(list)));
    list.value = type == 'up' ? up(index, arr) : down(index, arr);
  };

  //子表左侧新增
  const handleLeftAdd = ({ element }) => {
    console.log('element', element);
    element.childLeft.push(cloneDeep(leftAddRow));
  };
  //子表左侧删除
  const handleLeftDelete = ({ element, elIndex }) => {
    element.childLeft.splice(elIndex, 1);
  };

  //子表右侧新增
  const handleRightAdd = ({ element }) => {
    element.childRight.push(cloneDeep(rightAddRow));
  };
  //子表右侧删除
  const handleRightDelete = ({ element, elIndex }) => {
    element.childRight.splice(elIndex, 1);
  };

  //保存
  const handleSave = async () => {
    const { isValid, inp, views } = setviews(unref(list));
    console.log('setviews', { isValid, inp, views });
    if (!isValid) {
      return createMessage.warning(inp);
    }
    try {
      const params = {
        id: props.mainId,
        viewSetup: views,
      };
      loading.value = true;
      await getFormViewUpdateViewSetup(params);
      createMessage.success('操作成功');
      getAdminFlowGetViewRuleData();
    } catch (err) {
      console.log(err);
    } finally {
      loading.value = false;
    }
  };

  //点击菜单
  const handleClickMenu = (key, el) => {
    el['val'] = '';
    if (key == 'mainFormOpt') {
      el['mainFormOpt'] = true;
    } else {
      el['mainFormOpt'] = false;
      el['val'] = key.toString();

      const obj2 = itemKeys.find((k) => k.value == el['val']);
      if (obj2) {
        el['curTypeName'] = obj2?.label;
      }
    }
  };

  const formGetFields = ref<Recordable[]>([]);
  const formGetFieldsMain = ref<Recordable[]>([]);

  const getFormGetFieldsData = async () => {
    let params = {
      formCode: props.formCode,
    };
    if (!params.formCode) return;
    try {
      const data = (await getFormGetFields(params)) || [];
      formGetFields.value = data.map((item) => {
        delete item.options;
        return {
          ...item,
          label: item.title,
          value: item.name,
        };
      });
      formGetFieldsMain.value = data.map((item) => {
        delete item.options;
        return {
          ...item,
          label: item.title,
          value: item.name,
        };
      });
      formGetFields.value.unshift({
        label: '-角色-',
        value: 'cws_role',
      });
    } catch (err) {
      console.log('getFormGetFieldsData', err);
    }
  };

  //表单change
  const getFieldsChange = (val, el) => {
    el['mainFormOpt'] = false;
    el['val'] = '';
    if (val) {
      const obj = formGetFields.value.find((item) => item.value == val);
      el['fieldType'] = obj?.fieldType;
      el['formCode'] = obj?.formCode;
    } else {
      el['fieldType'] = '';
      el['formCode'] = '';
    }
  };

  //取得表单中的元素，包括控件、表格行、span、div
  const formElementsList = ref<Recordable[]>([]);
  const getFormGetFormElementsData = async () => {
    formElementsList.value = [];
    const data = await getFormViewGetElements({ id: props.mainId });
    if (isArray(data)) {
      formElementsList.value = data.map((item) => {
        return {
          ...item,
          label: item.tagTitle, // `${item.tagName}:${item.title}(${item.id})`,
          value: item.id,
        };
      });
    }
  };

  const model = ref({
    views: '',
  });
  const getAdminFlowGetViewRuleData = async () => {
    if (!props.formCode) return;
    try {
      loading.value = true;
      model.value = await getFormViewGetViewRule({ id: props.mainId });
      const { data } = getviews({
        views: unref(model).views,
      });
      list.value = data;
      console.log('list', list.value);
    } finally {
      loading.value = false;
    }
  };

  //获取角色
  const roleList = ref([]);
  async function getDataList() {
    await getRoleMultilSel().then((res) => {
      let data = res || [];
      data.forEach((item) => {
        item.value = item.code;
        item.label = item.description;
      });
      roleList.value = data;
    });
  }
  const fetch = async () => {
    await getFormGetFieldsData();
    await getAdminFlowGetViewRuleData();
    getFormGetFormElementsData();
    getDataList();
  };
  watch(
    () => props.formCode,
    async (newVal) => {
      console.log('DisplayRules-watch', newVal);
      await nextTick();
      fetch();
    },
    {
      immediate: true,
    },
  );
  onMounted(() => {
    console.log('DisplayRules-onMounted');
  });
</script>
